package leetcode;

import java.util.ArrayList;
import java.util.List;

public class N002AddTwoNumbers {
    public static void main(String[] args) {
        ListNode l2 = val2Node(new int[]{1, 5});
        ListNode l1 = val2Node(new int[]{0});
        ListNode result = addTwoNumbers(l1, l2);

        toString(result);
    }

    private static ListNode val2Node(int[] arr) {
        ListNode listNode = new ListNode(0);
        ListNode pre = listNode;
        for (int i = 0; i < arr.length; i++) {
            ListNode ln = new ListNode(arr[i]);
            pre.next = ln;
        }
        return listNode.next;
    }

    private static void toString(ListNode listNode) {
        ListNode start = listNode;
        List<Integer> list = new ArrayList<>();
        while (start != null) {
            list.add(start.val);
            start = start.next;
        }
        System.out.println(list);
    }

    static public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode result = new ListNode(0);
        ListNode a1 = l1;
        ListNode a2 = l2;
        ListNode current = result;
        int last = 0;

        while (a1 != null || a2 != null) {
            if (a1 == null) {
                a1 = new ListNode(0);
            }
            if (a2 == null) {
                a2 = new ListNode(0);
            }
            int v1 = a1 == null ? 0 : a1.val;
            int v2 = a2 == null ? 0 : a2.val;
            int sum = v1 + v2 + last;
            last = sum / 10;
            ListNode pre = new ListNode(sum % 10);
            current.next = pre;
            current = current.next;
            a1 = a1.next;
            a2 = a2.next;
        }

        if (last > 0) {
            current.next = new ListNode(last);
        }

        return result.next;
    }

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode(int x) { val = x; }
     * }
     */
    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

}

